class Jq {
    ajax(options) {
        return new Promise(resolve => {
            console.log("ajax执行了", options);
            // 给传入的参数默认参数；
            // 解构的同时给每个参数 默认参数；
            let { url = "", type = "get", data = {}, dataType = "json", success = function () { }, headers = { ['Content-Type']: "application/x-www-form-urlencoded" } } = options;
            // console.log(this.#o2s( data ));
            // 根据参数 利用原生的xmlhttprequest发送ajax；
            let xhr = new XMLHttpRequest();
            if (type === "get") {
                url = url + "?" + this.#o2s(data)
            }


            xhr.open(type, url);
            // 先open 在设置头部；
            // 循环设置 请求头部；
            for (let key in headers) {
                xhr.setRequestHeader(key, headers[key]);
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // console.log("成功");
                        if (dataType === "json") {
                            console.log(111);
                            success(JSON.parse(xhr.responseText))
                            resolve(JSON.parse(xhr.responseText));
                        } else {
                            success(xhr.responseText);
                            resolve(xhr.responseText);
                        }
                    }
                }
            }

            if (type === "get") {
                xhr.send();
            } else {
                // post
                if (headers['Content-Type'] === "application/json") {
                    console.log("?", data)
                    xhr.send(data);
                } else {
                    // name=zhangsan&age=20
                    xhr.send(this.#o2s(data));
                }
            }

        })

    }
    #o2s = obj => Object.keys(obj).map(item => `${item}=${obj[item]}`).join("&");
    get(url, data, cb, dataType) {
       return this.ajax({
            url,
            data,
            success: cb,
            dataType
        })
    }
}

let $ = new Jq();